var Hero = function(id, name, img, gold, health)
{
    this.id = id;
    this.name = name;
    this.gold = gold;
    this.health = health;
    this.img = img;

    //définie par le client
    this.level = -1;
    this.maxHealth = 42;
    this.tiles = [];
    this.buildings = [];
    this.crops = [];
    //utilisé pour l'update en db des timers de crops
    this.complexCrops = [];

    this.x = null;
    this.y = null;

    this.path = {
        start: {},
        stop: {},
        //  in path.steps :
        //  [0] -> current Tile (as Tile object),
        //  [1...n] -> path to destination (as Row & Col object)
        steps: [],
        simpleSteps: []
    };

    this.moveTimer = false;

    this.updateGolds = function(amount) {
        this.gold += amount;
    }

    this.updateLevel = function(amount) {
        this.level = this.tiles.length;

        cl_hero_update(this.asSimpleObject());
    }

    this.addTile = function(tile) {
        this.tiles.push(tile);
    }

    this.addBuilding = function(building) {
        this.buildings.push(building);
    }

    this.addCrop = function(crop) {
        this.crops.push(crop);
        crop.id = this.crops.length + 1;
    }
    this.addComplexCrop = function(crop) {
        this.complexCrops.push(crop);
        crop.id = this.complexCrops.length + 1;
    }
    this.removeCrop = function(crop) {
        for(var c in this.crops) {
            if(this.crops[c].pos.row == crop.pos.row && this.crops[c].pos.col == crop.pos.col) {
                this.crops.splice(c,1);
                this.complexCrops.splice(c,1);
            }
        }
    }

    this.drawHero = function(enemy) {
        if(enemy) {
            c.drawImage(this.img, this.x + camera.x, this.y + camera.y);
        }
        else {
            var coords =  {
                x: this.path.steps[0].x,
                y: this.path.steps[0].y
            }

            this.x = coords.x + (defaultTileWidth / 3);
            this.y = coords.y + (defaultTileHeight / 8);

            c.drawImage(this.img, (canvas.getWidth() / 2) , (canvas.getHeight() / 2));
        }
    }

    this.move = function() {
        var curHero = this;
        var framesCount = 18, i = 0;

        var nextTile = findTileByRowCol(curHero.path.steps[1].row, curHero.path.steps[1].col);

        var distX = (nextTile.x + (defaultTileWidth/3)) - this.x;
        var distY = (nextTile.y + (defaultTileHeight/8)) - this.y;

        var stepX = distX / framesCount;
        var stepY = distY / framesCount;

        this.moveTimer = setInterval(function() {
            if(i == framesCount) {
                clearInterval(curHero.moveTimer);
                curHero.moveTimer = false;
                // Le héros a été déssiné, on avance sa position et le tableau d'étapes
                curHero.proceedStep();
                // Si une étape suivante existe, on continue
                if(curHero.path.steps[1] != null) {
                    curHero.move();
                }
                return;
            }

            camera.x -= stepX;
            camera.y -= stepY;

            drawRange(findCurHeroTile(curHero), 9, true);

//            stepX = stepX + (distX / framesCount);
//            stepY = stepY + (distY / framesCount);

            i++;
        }, 33);
    }

    //enemy move event
    this.moveEnemy = function() {
        var curHero = this;

        var framesCount = 18, i = 0;

        var nextTile = findTileByRowCol(curHero.path.simpleSteps[1].row, curHero.path.simpleSteps[1].col);

        var distX = (nextTile.x + (defaultTileWidth/3)) - this.x;
        var distY = (nextTile.y + (defaultTileHeight/8)) - this.y;

        var stepX = distX / framesCount;
        var stepY = distY / framesCount;

        this.moveTimer = setInterval(function() {
            if(i == framesCount) {
                clearInterval(curHero.moveTimer);
                curHero.moveTimer = false;
                // Le héros a été déssiné, on avance sa position et le tableau d'étapes
                curHero.proceedEnemyStep();
                // Si une étape suivante existe, on continue
                if(curHero.path.simpleSteps[1] != null) {
                    curHero.moveEnemy();
                }
                return;
            }

            curHero.x += stepX;
            curHero.y += stepY;

            curHero.drawHero(true);
            //on draw un range d'1 tile autour de l'énemi
            var drawTile = findTileByRowCol(curHero.path.simpleSteps[1].row, curHero.path.simpleSteps[1].col);
            drawRange(drawTile, 1);

//            stepX = stepX + (distX / framesCount);
//            stepY = stepY + (distY / framesCount);

            i++;
        }, 33);
    }

    this.proceedStep = function() {
        //On send au srv la nouvelle pos du héros avant de continuer le parcours
        var newPos = this.path.steps[1];
        cl_proceedStep_event(this.asSimpleObject(), newPos);

        this.path.steps[0] = findTileByRowCol(hero.path.steps[1].row, hero.path.steps[1].col);
        this.x = this.path.steps[0].x + (defaultTileWidth/3);
        this.y = this.path.steps[0].y + (defaultTileHeight/8);

        var rowCol = findRowCol(this.path.steps[0]);
        this.path.start.x = rowCol.row;
        this.path.start.y = rowCol.col;

        for(var i = 1; i < this.path.steps.length; i++) {
            if(this.path.steps[i + 1] != null) {
                this.path.steps[i] = this.path.steps[i + 1];
            }
            else {
                this.path.steps[i] = null;
                this.path.steps.length = i;
            }
        }
    }

    this.proceedEnemyStep = function() {
        this.path.simpleSteps[0] = findTileByRowCol(this.path.simpleSteps[1].row, this.path.simpleSteps[1].col);
        this.x = this.path.simpleSteps[0].x + (defaultTileWidth/3);
        this.y = this.path.simpleSteps[0].y + (defaultTileHeight/8);

        var rowCol = findRowCol(this.path.simpleSteps[0]);
        this.path.start.x = rowCol.row;
        this.path.start.y = rowCol.col;

        for(var i = 1; i < this.path.simpleSteps.length; i++) {
            if(this.path.simpleSteps[i + 1] != null) {
                this.path.simpleSteps[i] = this.path.simpleSteps[i + 1];
            }
            else {
                this.path.simpleSteps[i] = null;
                this.path.simpleSteps.length = i;
            }
        }
    }

//    this.getHeroLeaveState = function() {
//        //on up en db les timers des crops afin de reprendre a ceux ci une fois que l'user se reco
//        for(var c in this.crops) {
//            this.crops[c].updateState();
//        }
//
//        return this.asSimpleObject();
//    }

    this.updCropsTimers = function() {
        for(var c in this.complexCrops) {
            this.complexCrops[c].updateState();
            this.crops[c].timeRemaining = this.complexCrops[c].timeRemaining;
        }
    }

    //print step for enemy move event
//    this.printSteps = function() {
//        console.log('--- enemy Steps ---');
//        for(var i = 1; i < this.path.simpleSteps.length; i++) {
//            console.log('n'+i+' : '+this.path.simpleSteps[i].row+','+this.path.simpleSteps[i].col);
//        }
//    }

    this.computeStats = function() {
        this._computeLevel();
        this._computeHealth();
    }
        this._computeLevel = function() {
            this.level = this.tiles.length;
            return this.level;
        }
        this._computeHealth = function() {
            this.maxHealth = this.level * 42;
            return this.maxHealth;
        }


    //cl_events JSON debugging
    this.asSimpleObject = function() {
        this.computeStats();
        return {
            id: this.id,

            name: this.name,

            gold: this.gold,
            level: this.level,
            health: this.health,
            maxHealth: this.maxHealth,

            tiles: this.tiles,
            crops: this.crops,
            buildings: this.buildings
        }
    }
}

function findHeroById(id) {
    for(var h in enemyHeroes) {
        if(enemyHeroes[h].id == id) return enemyHeroes[h];
    }

    return null;
}